package com.salesmanager.core.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by Liutong on 1/12/16.
 */
public class HttpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    /**
     *
     * @param url
     * @return
     */
    public static String getResponseBody(String url){
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000)
                    .setConnectTimeout(5000).build();//设置请求和传输超时时间

            get.setConfig(requestConfig);

            HttpResponse httpResponse = httpClient.execute(get);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                HttpEntity httpEntity = httpResponse.getEntity();

                if (httpEntity != null){
                    StringBuilder entityStringBuilder = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader
                            (new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
                    String line;
                    while ((line=bufferedReader.readLine())!=null) {
                        entityStringBuilder.append(line);
                    }
                    bufferedReader.close();
                    return entityStringBuilder.toString();
                }
            }
        } catch (Exception e){
            LOGGER.error("HttpUtils.getRequestBody Error!",e);
        }

        return null;
    }


    public static void main(String[] args){
        String  body = getResponseBody("http://redirect.simba.taobao.com\\/rd?&f=http%3A%2F%2Fai.taobao.com%2Fauction%2Fedetail.htm%3Fe%3DgVvbg655EonuDAZjWhpTWPuo79XlJwxIUdxTnhZJMiJBWJVBnwmj7rIcGym4S3j1mjXyGiP6gLsEwiwEAUVRm6wx2tCML0KPhcHZvKC0yiukJIbEz1DU6R6IQnsDfLM6PiXrXe4MzbStLLLOu9oFnQ%253D%253D%26ptype%3D100011%26rType%3D1%26from%3Dgoldenlink%26eid%3D&k=5ccfdb950740ca16&p=mm_111813377_10722027_35302573&pvid=526017193308&posid=&b=display_1_625_0_0_0&w=unionapijs&c=un");
        System.out.println(body);
    }
}
